import { URLSearchParamsInit, useSearchParams } from "react-router-dom";
import { useMemo } from "react";
import { clearObject } from "./index";

/**
 * 返回页面url, 指定键的返回值
 * */
export const useUrlQueryParam = <K extends string> (keys: K[]) => {
  const [searchParams, setSearchParams] = useSearchParams();
  return [
    useMemo(
      () => keys.reduce((prev, key) => {
        return { ...prev, [key]: searchParams.get(key) || "" };
      }, {} as { [key in K]: string }),
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [searchParams]
    ),
    (params: Partial<{[key in K]: unknown}>) => {
        // iterator
        const o = clearObject({...Object.fromEntries(searchParams), ...params}) as URLSearchParamsInit
        return setSearchParams(o)
    }
  ] as const;
};
